﻿using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Yuebon.Commons.Helpers;
using Yuebon.Commons.Log;
using Yuebon.Quartz.Jobs;

namespace Yuebon.Quartz
{
    /// <summary>
    /// 添加调用任务，调度器
    /// </summary>
    public class YuebonScheduler
    {
        static YuebonScheduler _instance = null;
        static object lockObj = new object();

        /// <summary>
        /// 线程安全的单例对象
        /// </summary>
        public static YuebonScheduler Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (lockObj)
                    {
                        if (_instance == null)
                        {
                            _instance = new YuebonScheduler();
                        }
                    }
                }
                return _instance;
            }
        }

        public static async Task Start()
        {
            try
            {
                // Grab the Scheduler instance from the Factory    
                NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" }
                };
                StdSchedulerFactory factory = new StdSchedulerFactory(props);
                IScheduler scheduler = await factory.GetScheduler();


                // 启动任务调度器    
                await scheduler.Start();
                // 定义一个 Job    
                IJobDetail job = JobBuilder.Create<AutoErpToMesJob>().WithIdentity("job1", "group1").Build();
                ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                    .WithIdentity("trigger1") // 给任务一个名字    
                    .StartAt(DateTime.Now) // 设置任务开始时间    
                    .ForJob("job1", "group1") //给任务指定一个分组    
                    .WithSimpleSchedule(x => x
                    .WithIntervalInHours(4)  //循环的时间 1秒1次   
                    .RepeatForever())
                    .Build();


                // 等待执行任务    
                await scheduler.ScheduleJob(job, trigger);


            }
            catch (SchedulerException ex)
            {
                var type = MethodBase.GetCurrentMethod().DeclaringType;
                Log4NetHelper.WriteError(type, ex);
            }
        }

    }
}
